package com.cn.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@WebServlet(value="/UploadFileUtil")
public class UploadFileUtil extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		//判断是否为上传文件
		if(ServletFileUpload.isMultipartContent(req)){
			//需要使用我们硬盘文件工厂
			DiskFileItemFactory factory=new DiskFileItemFactory();
			
			//获取文件上传类
			ServletFileUpload upload=new ServletFileUpload();
					
			//调用ServletFileUpload中的paraseRequest(request<其实这里是将request.getInputStream()做了封装>)
			try {
				List<FileItem> fileItem=upload.parseRequest(req);
				Iterator it=fileItem.iterator();
				while(it.hasNext()) {
					FileItem item=(FileItem)it.next();
					if(item.isFormField()){//text类型
						System.out.println("不是文件,而是文本!!!");
					}else {//文件类型
						String fileName=item.getName();
						String path=req.getServletContext().getRealPath("/uploadFiles");
						File file=new File(path,fileName);
						item.write(file);	
						System.out.println("上传成功!");
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doGet(req, resp);
	}
}
